Micron Document




Java ConcurrentMap
part 7/19 · 30.6 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
The synchronization of the iteration is recommended as follows; however, this synchronizes on the wrapper rather than on the internal mutex, allowing overlap:cite-ref-5[5]

Map<String, String> wrappedMap = Collections.synchronizedMap(map);
...
synchronized (wrappedMap) {
for (final String s : wrappedMap.keySet()) {
// some possibly long operation executed possibly
// many times, delaying all other accesses
}
}

Native synchronization

Any Map can be used safely in a multi-threaded system by ensuring that all accesses to it are handled by the Java synchronization mechanism:

final Map<String, String> map = new HashMap<>();
...
// Thread A
// Use the map itself as the lock. Any agreed object can be used instead.
synchronized(map) {
map.put("key","value");
}
..
// Thread B
synchronized (map) {
String result = map.get("key");
...
}
...
// Thread C
synchronized (map) {
for (final Entry<String, String> s : map.entrySet()) {
/*
* Some possibly slow operation, delaying all other supposedly fast operations.
* Synchronization on individual iterations is not possible.
*/
...
}
}

ReentrantReadWriteLock

──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────